<!DOCTYPE html>
<html>

	<head>
		<title>知识导入</title>
		#include("common/head.html")
		<link rel="stylesheet" type="text/css" href="resource/webuploader/webuploader.css">
		<!--引入JS-->
		<script type="text/javascript" src="resource/webuploader/webuploader.js"></script>
	</head>

	<body>
		<div class="am-cf admin-main" style="padding: 0;">
			<!-- sidebar start -->
			<!-- sidebar end -->
			<!-- content start -->
			<div class="admin-content">
				<div class="admin-content-body">
					<div class="am-cf am-padding">
						<div class="am-fl am-cf">
							<strong class="am-text-primary am-text-lg">导入知识</strong> / <small>支持文件的批量上传及压缩包导入，支持Office文档、PDF、图像、音视频和图纸等各类型文件。(注：单个文件不超过100MB)</small>
						</div>
					</div>

					<div class="am-u-sm-12">

						<div id="uploader" class="wu-example">
							<!--用来存放文件信息-->
							<div id="thelist" class="uploader-list"></div>
							<div class="btns">
								<div id="picker">添加文件</div>
								<!--
								<div id="unc-div" style="display: none;" class="am-alert am-alert-secondary" data-am-alert>
									<span class="am-icon-question-circle-o"></span> 您选择的文件中含有压缩文件，请选择导入方式：
									<button class="if-unc" type="button" class="am-btn am-btn-xs am-btn-primary" data-am-button>导入压缩包</button>
									<script>
										$(function() {
											$.post("user/re-compress")
											var $toggleButton = $('.if-unc');
											$toggleButton.on('click', function() {
												setButtonStatus();
											});

											function setButtonStatus() {
												$.post("user/tog-compress", function(data) {
													if(data == "success") {
														var status = $toggleButton.hasClass('am-active') ? '解压导入' : '导入压缩包';
														$('.if-unc').text(status);
													}
												})
											}
										})
									</script>
								</div>
								-->
								<button id="ctlBtn" class="am-btn am-btn-warning am-radius">开始导入</button>
							</div>
						</div>

					</div>

				</div>
			</div>
			<!-- content end -->
		</div>
		<div class="am-modal am-modal-loading am-modal-no-btn" tabindex="-1" id="info-modal">
			<div class="am-modal-dialog">
				<div class="am-modal-hd">上传成功...</div>
				<div class="am-modal-bd">
					<span class="am-icon-spinner am-icon-spin"></span>
				</div>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		$(window).bind('beforeunload', function() {
			return '您输入的内容尚未保存，确定离开此页面吗？';
		});
		$list = $('#thelist'), $btn = $('#ctlBtn'), state = 'pending', uploader;

		var fileMd5;
		var fileName;
		//监听分块上传过程中的三个时间点
		WebUploader.Uploader.register({
			"before-send-file": "beforeSendFile",
			"before-send": "beforeSend",
			"after-send-file": "afterSendFile",
		}, {
			//时间点1：所有分块进行上传之前调用此函数
			beforeSendFile: function(file) {
				var deferred = WebUploader.Deferred();
				//1、计算文件的唯一标记，用于断点续传
				(new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024)
					.progress(function(percentage) {
						$('#thelist').find("p.state").text("正在读取文件信息...");
					})
					.then(function(val) {
						fileMd5 = val;
						fileName = file.name;
						$('#thelist').find("p.state").text("成功获取文件信息...");
						//获取文件信息后进入下一步
						deferred.resolve();
					});
				return deferred.promise();
			},
			//时间点2：如果有分块上传，则每个分块上传之前调用此函数
			beforeSend: function(block) {
				var deferred = WebUploader.Deferred();

				$.ajax({
					type: "POST",
					url: "#(ctx)/apis/file/upload?action=checkChunk",
					data: {
						//文件唯一标记
						fileMd5: fileMd5,
						//当前分块下标
						chunk: block.chunk,
						//当前分块大小
						chunkSize: block.end - block.start
					},
					dataType: "json",
					success: function(response) {
						if(response.ifExist) {
							//分块存在，跳过
							deferred.reject();
						} else {
							//分块不存在或不完整，重新发送该分块内容
							deferred.resolve();
						}
					}
				});

				this.owner.options.formData.fileMd5 = fileMd5;
				deferred.resolve();
				return deferred.promise();
			},
			//时间点3：所有分块上传成功后调用此函数
			afterSendFile: function() {
				//如果分块上传成功，则通知后台合并分块
				$.ajax({
					type: "POST",
					url: "#(ctx)/apis/file/upload?action=mergeChunks",
					data: {
						fileMd5: fileMd5,
						fileName: fileName,
						catalogId: #(id??'1')
					},
					success: function(response) {
						var path = response.fileurl; //basePath + "/uploadFile/" + fileMd5 + ".mp4";
						$("#thelist").attr("src", path);
						refreshFileList();
						setTimeout(function() {
							$(".uploadBox").hide();
						}, 1000);
					}
				});
			}
		});

		var uploader = WebUploader.create({
			// swf文件路径
			swf: '#(ctx)/static/libs/webuploader-0.1.5/Uploader.swf', //'resource/webuploader/Uploader.swf',
			// 文件接收服务端。
			server: '#(ctx)/apis/file/uploadSect',
			// 选择文件的按钮。可选。
			// 内部根据当前运行是创建，可能是input元素，也可能是flash.
			pick: '#picker',
			// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
			//resize: false,
			//fileSingleSizeLimit: 104857600 //大小限制 100M
			// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
			resize: true,
			//auto: true,
			//开启分片上传
			chunked: true,
			chunkSize: 10 * 1024 * 1024,
		});

		// 当有文件被添加进队列的时候
		uploader
			.on(
				'fileQueued',
				function(file) {
					$list
						.append('<div id="' + file.id + '" class="am-panel am-panel-secondary" style="margin-bottom:3px">' +
							'<div class="am-panel-hd">' +
							'<span class="state am-badge am-badge-secondary">等待上传...</span>' +
							" 文件名： " + file.name + '    大小：' + (file.size / 1024 / 1024).toFixed(2) + ' MB </div>' +

							'</div>');
					if(file.ext == "zip" || file.ext == "rar") {
						$("#unc-div").show("fast");
					}
				});
		// 文件上传过程中创建进度条实时显示。
		uploader
			.on(
				'uploadProgress',
				function(file, percentage) {
					var $li = $('#' + file.id),
						$percent = $li
						.find('.am-progress .am-progress-bar');

					// 避免重复创建
					if(!$percent.length) {

						$percent = $(
								'<div class="am-progress am-progress-striped  am-active">' +
								'<div class="am-progress-bar am-progress-bar-secondary"  style="width: 0%">' +
								'</div>' + '</div>')
							.appendTo($li).find('.am-progress-bar');
					}

					$li.find('span.state').text('上传中');
					var res = (percentage * 100).toFixed(2);
					$li.find('.am-progress-bar-secondary').text(res + "%");
					$percent.css('width', percentage * 100 + '%');
				});
		$btn.on('click', function() {
			if(state === 'uploading') {
				uploader.stop();
			} else {
				uploader.upload();
			}
		});

		uploader.on('uploadSuccess', function(file) {
			var $li = $('#' + file.id);
			$li.find('span.state').text('已上传');
			$percent = $li.find('.am-progress');
			$bar = $li.find('.am-progress-bar');
			$percent.removeClass("am-active").removeClass("am-progress-striped");
			$bar.addClass("am-progress-bar-success");
			$("#unc-div").hide("fast");
		});

		uploader.on('uploadError', function(file) {
			var $li = $('#' + file.id);
			$li.find('p.state').text('上传出错');
			$percent = $li.find('.am-progress');
			$bar = $li.find('.am-progress-bar');
			$percent.removeClass("am-active").removeClass("am-progress-striped");
			$bar.addClass("am-progress-bar-danger");
			$("#unc-div").hide("fast");
		});

		uploader.on('uploadComplete', function(file) {
			$('#' + file.id).find('.progress').fadeOut();
		})

		uploader.on('uploadFinished', function(file) {
			$("#info-modal").modal();
			$(window).unbind('beforeunload');
			setTimeout(function() {
				window.location.href = "#(ctx)/user/uploadFinish";
			}, 1500);

		})
	</script>

</html>